//package com.example.robot;
//
//import com.enmoli.activity.data.AsAdminActivity;
//import com.enmoli.activity.data.redis.SpringEventMsg;
//import com.enmoli.activity.data.repository.AsAdminActivityRepository;
//import com.enmoli.activity.redis.ActivityRedisKey;
//import com.enmoli.activity.utils.RedisUtil;
//import com.enmoli.core.util.DateUtil;
//import com.enmoli.core.util.JsonUtil;
//import com.google.common.collect.Lists;
//import com.google.common.collect.Maps;
//import org.apache.http.client.config.RequestConfig;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClientBuilder;
//import org.apache.http.util.EntityUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.event.EventListener;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.stereotype.Component;
//import java.io.IOException;
//import java.time.Instant;
//import java.time.LocalDateTime;
//import java.time.ZoneId;
//import java.time.format.DateTimeFormatter;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.TimeUnit;
//
//@Component
//public class RobotService {
//    private static final Logger log = LoggerFactory.getLogger(RobotService.class);
//
//    @Autowired
//    private AsAdminActivityRepository activityRepository;
//    @Value("${activity.notify.webhook.url:https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f3f46054-1b7d-4721-b89c-11cf407453af}")
//    private String webhook;
//    @Value("${activity.notify.webhook.url.2:https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=eb43dbb8-6519-4d24-b29e-85b0f880c4bb}")
//    private String webhook2;
//    @Value("${activity.notify.webhook.url.3:https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d92951d9-9626-4425-b6c2-9329389522f0}")
//    private String webhook3;
//    @Value("${activity.notify.enabled:false}")
//    private Boolean notifyEnable;
//
//    @Value("#{'${activity.notify.game.category.list:9, 12, 6, 16, 7, 14, 2, 19, 22, 20}'.split(',')}")
//    private List<Integer> notifyGameCategoryList;
//    @Autowired
//    @Qualifier("activityRedisTemplate")
//    private StringRedisTemplate activityRedisTemplate;
//
//    public void sendActivityNotice() {
//        if (!notifyEnable) {
//            log.info("activityNotice not send");
//            return;
//        }
//        // 1.即将开始的活动，2.即将结束的活动
//        List<AsAdminActivity> activities = activityRepository.findValidActivities();
//        Integer dateline = DateUtil.currentDateline();
//        for (AsAdminActivity activity : activities) {
//            Integer beginTime = activity.getBeginTime();
//            Integer endTime = activity.getEndTime();
//            String begin = DateUtil.DATE_SECONDS_TIME_FORMAT.format(beginTime*1000L);
//            String end = DateUtil.DATE_SECONDS_TIME_FORMAT.format(endTime*1000L);
//            activity.setBeginTime(null);activity.setEndTime(null);
//            // 12个小时内要开始的活动
//            if (beginTime >= dateline && beginTime <= dateline + 43200) {
//                sendGroupMessage("秀色-即将开始的活动：" + begin + "——" + end + "\n" + JsonUtil.toJson(activity));
//            }
//            // 12个小时内要结束的活动
//            if (endTime >= dateline && endTime <= dateline + 43200) {
//                sendGroupMessage("秀色-即将结束的活动：" + begin + "——" + end + "\n" + JsonUtil.toJson(activity));
//            }
//        }
//        //
//        LocalDateTime now = LocalDateTime.now();
//        if(now.getHour() == 20){ // redis 记录一下
//            int dayOfMonth = now.getDayOfMonth();
//            int month = now.getMonthValue();
//            String cornKey = String.format("activity:211:corn:%s:%s", month, dayOfMonth);
//            activityRedisTemplate.opsForValue().set(cornKey, "1");
//            activityRedisTemplate.expire(cornKey, 7, TimeUnit.DAYS);
//        }
//    }
//
//    /**
//     * 游戏类活动单独通知，游戏类活动在活动开始前一天(12点)及当天的十点（10）在指定群里进行上线前提示；游戏类活动在活动结束前一小时（23）提示；
//     * 目前固定此范围）
//     *   砸蛋：双倍、阿拉丁、龙珠； 9,砸蛋双倍;12 阿拉丁;6,龙珠传奇;
//     *   世界游戏：豪门盛宴、夺宝、封侯拜相、武侠争霸、星球大战、疯狂赛车、悠闲钓鱼；16,豪门盛宴;7,夺宝奇兵;14,封侯拜相;2,武侠争霸;19,星球大战;22,F16;20,钓鱼;
//     * @param type 1：提醒今天要开始的活动。2：提醒明天要开始的活动。3：结束前一小时（23）提示
//     */
//    public void sendActivityNotice2(int type) {
//        if (!notifyEnable) {
//            log.info("sendActivityNotice2 not send");
//            return;
//        }
//        List<Long> aids = Lists.newArrayList();
//        for (Integer category : notifyGameCategoryList) {
//            Double score = activityRedisTemplate.boundZSetOps(ActivityRedisKey.CATEGORY_KEY).score(category.toString());
//            if (score == null) {
//                log.error("activity aid not found, category={}", category);
//                continue;
//            }
//            aids.add(score.longValue());
//        }
//
//        List<AsAdminActivity> activities = activityRepository.findActivitiesByIds(aids);
//        Integer dateline = DateUtil.currentDateline();
//        for (AsAdminActivity activity : activities) {
//            String begin = DateUtil.DATE_SECONDS_TIME_FORMAT.format(activity.getBeginTime()*1000L);
//            String end = DateUtil.DATE_SECONDS_TIME_FORMAT.format(activity.getEndTime()*1000L);
//            if (type == 1) {
//                // 提醒今天要开始的活动
//                Long todayEnd = DateUtil.getDayEndTime(new Date()).getTime() / 1000L;
//                if (activity.getBeginTime() >= dateline && activity.getBeginTime() <= todayEnd) {
//                    sendGroupMessage("秀色-今天开始的活动：" + begin + "——" + end + "\n" + JsonUtil.toJson(activity), webhook2);
//                }
//            } else if (type == 2) {
//                // 提醒明天开始的活动
//                Long tomorrowBegin = DateUtil.getDayEndTime(new Date()).getTime() / 1000L + 1;
//                Long tomorrowEnd = tomorrowBegin + 86400 - 1;
//                if (activity.getBeginTime() >= tomorrowBegin && activity.getBeginTime() <= tomorrowEnd) {
//                    sendGroupMessage("秀色-明天开始的活动：" + begin + "——" + end + "\n" + JsonUtil.toJson(activity), webhook2);
//                }
//            } else if (type == 3) {
//                // 结束前1小时提醒，活动都在23：59：59s结束
//                if (activity.getEndTime() >= dateline && activity.getEndTime() <= dateline + 43200) {
//                    sendGroupMessage("秀色-即将结束的活动：" + begin + "——" + end + "\n" + JsonUtil.toJson(activity), webhook2);
//                }
//            }
//        }
//    }
//
//
//    /**
//     * 企业微信群机器人推文本消息
//     */
//    public void sendGroupMessage(String text) {
//        sendGroupMessage(text, webhook);
//    }
//
//    private void sendGroupMessage(String text, String webhook) {
//        log.info("sendGroupMessage text={}, webhook={}", text, webhook);
//        if (!notifyEnable) {
//            return;
//        }
//        HttpPost httpPost = new HttpPost(webhook);
//        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
//
//        Map<String, Object> postBody = Maps.newHashMapWithExpectedSize(2);
//        postBody.put("msgtype", "text");
//        postBody.put("text", buildMessageContext(text));
//        httpPost.setEntity(new StringEntity(JsonUtil.toJson(postBody),"UTF-8" ));
//
//        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).build();
//        httpPost.setConfig(requestConfig);
//
//        RobotMessageResponse response = null;
//        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//             CloseableHttpResponse responseEntity = httpClient.execute(httpPost)) {
//            response = JsonUtil.fromJson(EntityUtils.toString(responseEntity.getEntity()), RobotMessageResponse.class);
//            if (response.getErrcode() == 0) {
//            } else {
//                log.error("sendGroupMessage error, response={}", JsonUtil.toJson(requestConfig));
//            }
//        } catch (IOException e) {
//            log.error("getAcsResponse error", e);
//        }
//    }
//
//    private Map<String, String> buildMessageContext(String context) {
//        Map<String, String> message = new HashMap<>();
//        message.put("content", context);
//        message.put("mentioned_list", "");
//        return message;
//    }
//
//    private static class RobotMessageResponse {
//        private Integer errcode;
//        private String errmsg;
//
//        public Integer getErrcode() {
//            return errcode;
//        }
//
//        public void setErrcode(Integer errcode) {
//            this.errcode = errcode;
//        }
//
//        public String getErrmsg() {
//            return errmsg;
//        }
//
//        public void setErrmsg(String errmsg) {
//            this.errmsg = errmsg;
//        }
//    }
//
//
//    @Autowired
//    private RedisUtil redisUtil;
//
//    @Async
//    @EventListener
//    public void handlePrivateMsgEvent(SpringEventMsg event){
//        Integer time = event.getTime();
//        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(time), ZoneId.systemDefault());
//        int dayOfYear = localDateTime.getDayOfYear();
//        String redisKey = String.format("ac:%s:%s:%s", event.getAid(), event.getDiff(), dayOfYear);
//        if(notifyEnable && !redisUtil.exists(redisKey)){
//            redisUtil.setEx(redisKey, "1", 1, TimeUnit.DAYS);
//            String text = "秀色-"+event.getTitle()+": "+event.getDesc()+"\t"
//                    +localDateTime.format(DateTimeFormatter.ofPattern("MM月dd日 HH:mm:ss"))+" aid="+event.getAid();
//            sendGroupMessage(text);
//            // 奖池单独通知
//            if (event.getEventType() != null && event.getEventType().equals(1)) {
//                sendGroupMessage(text, webhook2);
//                sendGroupMessage(text, webhook3);
//            }
//        }
//    }
//}
